package com.agent.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DateUtil {

    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final SimpleDateFormat date_Time_Format = new SimpleDateFormat(
            DATE_TIME_FORMAT);

    public static final int monringBegin = 9; // 上午开始
    public static final int monringEnd = 12; // 上午结束
    public static final int afternoonBegin = 13; // 下午开始
    public static final int afternoonEnd = 17;// 下午结束
    public static final int afternoonEndMinutes = 30;// 下午结束分钟
    public static final long dayMs = new Double(7.5 * 60 * 60 * 1000).longValue(); // 一天工作时长的毫秒数

    public static Date parseDate(String dateStr, String pattern) {
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        try {
            return df.parse(dateStr);
        } catch (ParseException e) {
           log.error("com.agent.util.DateUtil.parseDate error|",e);
        }
        return null;
    }

    /**
     * 是否工作日   周一到周五 17.30之后   9点之前
     * @return
     */
    public static boolean isWorkDate(){
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if((date.getHours() == 17 && date.getMinutes() >= 30) || date.getHours()>17 || date.getHours()<9 || week == 1 || week ==7){
            return false;
        }
        return true;
    }

    public static long diffSecond(Date beginDate,Date now){
        return (now.getTime()-beginDate.getTime())/1000;
    }

    /**
     * 获取两个日期之间的所有日期（yyyy-MM-dd）
     * @param begin
     * @param end
     * @return
     */
    public static List<Date> getBetweenDates(Date begin, Date end) {
        List<Date> result = new ArrayList<Date>();
        while(begin.getTime() <= end.getTime()){
            result.add(begin);
            begin = DateUtils.addDays(begin,1);
        }
        return result;
    }

    /**
     *
     * @param hours
     * @param monring  true：上午 false：下午
     * @return
     */
    public static boolean isMonringOrAfternoon(int hours ,int minutes,boolean monring){
        if(monring){
            return hours>=monringBegin && (hours<monringEnd || (hours==monringEnd && minutes == 0));
        }else {
            return hours>=afternoonBegin && (hours<afternoonEnd || (hours == afternoonEnd && minutes<=afternoonEndMinutes));
        }
    }

    /**
     * 是否下班时间
     * @param hours
     * @param minutes
     * @return
     */
    public static boolean isOffWork(int hours ,int minutes){
        return (hours >17) || (hours==17 && minutes >=30);
    }
    // 转换为 分 秒
    public static String parseTime(long time){
        long minute = time / 1000 / 60;
        long secone = time / 1000 % 60;
        return minute+"分"+secone+"秒";
    }

    public static void main(String[] args) {
        Date begin = new Date();
//        begin = DateUtils.addDays(begin,-1);
        begin.setHours(13);
        begin.setMinutes(24);
        begin.setSeconds(15);
        Date end = new Date();
        end.setHours(12);
        end.setMinutes(00);
        end.setSeconds(38);
//        List<Date> betweenDates = DateUtil.getBetweenDates(begin, end);
//        System.out.println(betweenDates);
        Long aLong = DateUtil.reduceWorkDayMs(begin, end, new ArrayList<>());
        System.out.println(aLong);
        System.out.println(DateUtil.parseTime(aLong));
    }


    /**
     * 计算两个时间之间的工作时间  工作时间09：00-12：00 13：00-17：30
     * @param beginTime
     * @param endTime
     * @param noWorkDateList 非工作日集合
     * @return
     */
    public static Long reduceWorkDayMs(Date beginTime,Date endTime,List<Date> noWorkDateList){
        int beginTimeHours = beginTime.getHours(); // 开始时间的小时
        int endTimeHours = endTime.getHours(); // 结束时间 小时
        int beginTimeMinutes = beginTime.getMinutes();// 开始时间分钟
        int endTimeMinutes = endTime.getMinutes();// 结束时间分钟
        if(DateUtils.isSameDay(beginTime, endTime)){ // 同一天
            if(endTime.getTime() > beginTime.getTime()){
                // 根据时间间隔 是否相差12-13为准
                if(beginTimeHours < 12 && endTimeHours>=13){
                    long ms = (afternoonBegin - monringEnd) * 60 * 60 * 1000L;
                    return endTime.getTime() - beginTime.getTime() - ms;
                }else if(beginTimeHours == 12 && endTimeHours == 12){ // 都是午休时间
                    return 0L;
                } else if(isOffWork(beginTimeHours,beginTimeMinutes) && isOffWork(endTimeHours,endTimeMinutes) ){ // 都是下班时间
                    return 0L;
                }else{
                    return endTime.getTime() - beginTime.getTime();
                }
            }
        }else { // 不是同一天  先计算 开始日的工作时间+结束日的工作时间  在根据两天之间的差值 排除掉非工作日 计算出天数差
            Date offWork = new Date(beginTime.getTime()); // 下班时间
            offWork.setHours(afternoonEnd);
            offWork.setMinutes(afternoonEndMinutes);
            long beginOffWorkTime = 0l;
            if(isMonringOrAfternoon(beginTimeHours,beginTimeMinutes,true)){// 上午
                long ms = (afternoonBegin - monringEnd) * 60 * 60 * 1000L; // 去除12:00 - 13:00 之间的时间差
                beginOffWorkTime = offWork.getTime() - beginTime.getTime()-ms;
            }else if(beginTimeHours==12 && beginTimeMinutes>0){ // 开始时间在12-13之间  则按照13处理
                Date date_13 = new Date(beginTime.getTime()); // 下班时间
                date_13.setHours(afternoonBegin);
                date_13.setMinutes(0);
                beginOffWorkTime = offWork.getTime() - date_13.getTime();
            }else{ // 下午
                if(beginTime.getTime() <= offWork.getTime()){
                    beginOffWorkTime = offWork.getTime() - beginTime.getTime();
                }
            }
            Date inWork = new Date(endTime.getTime()); // 上班时间
            inWork.setHours(monringBegin);
            inWork.setMinutes(0);
            long endInWorkTime = 0l;
            if(isMonringOrAfternoon(endTimeHours,endTimeMinutes,true)){// 上午
                endInWorkTime = endTime.getTime() - inWork.getTime();
            } else if(isMonringOrAfternoon(endTimeHours,endTimeMinutes,false)){// 下午
                long ms = (afternoonBegin - monringEnd) * 60 * 60 * 1000L; // 去除12:00 - 13:00 之间的时间差
                endInWorkTime = endTime.getTime() - inWork.getTime() - ms;
            }else if(isOffWork(endTimeHours,endTimeMinutes)){ // 结束在下班之后
                endInWorkTime = dayMs;
            }else if(endTimeHours==12 && endTimeMinutes>0){  //结束时间在12-13之间  则按照12处理
                Date date_12 = new Date(beginTime.getTime()); // 下班时间
                date_12.setHours(monringEnd);
                date_12.setMinutes(0);
                endInWorkTime = date_12.getTime() - inWork.getTime();
            }else{
                endInWorkTime = endTime.getTime() - inWork.getTime();
            }
            // 获取两天之间的 工作日天数
            List<Date> dateList = getBetweenDates(beginTime, endTime);
            List<Date> collect = dateList.stream().filter(date -> {
                return !DateUtils.isSameDay(date, beginTime) && !DateUtils.isSameDay(date, endTime); // 去掉起始日期和结束日期
            }).filter(date -> {
                Boolean isSameDay = true;
                for (Date date1 : noWorkDateList) {
                    if (DateUtils.isSameDay(date, date1)) {
                        isSameDay = false;
                    }
                }
                return isSameDay;
            }).collect(Collectors.toList());
            return dayMs * collect.size() + beginOffWorkTime + endInWorkTime;
        }
        return 0l;
    }

}
